#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <fcntl.h>

using namespace std;
using namespace SocketModule;
using namespace LogModule;

using ioserver_t = function<void(shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, ioserver_t server)
        : _port(port),
          _server(server),
          _running(false),
          _sock(make_unique<TcpSocket>())
    {
        _sock->BuildTcpSocketMethod(_port);
    }

    void Start()
    {
        _running = true;
        while (_running)
        {
            InetAddr client;
            auto sock = _sock->accept(&client); // 1. 和client通信sockfd 2. client 网络地址
            if (sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success ..." << client.StringAddr();

            // sock && client
            pid_t id = fork();
            if (id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error ...";
                exit(FORK_ERR);
            }
            else if (id == 0)
            {
                // 子进程 -> listensock
                _sock->Close();
                if (fork() > 0)
                    exit(OK);
                // 孙子进程在执行任务，已经是孤儿了
                _server(sock, client);
                sock->Close();
                exit(OK);
            }
            else
            {
                // 父进程 -> sock
                sock->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
                (void)rid;
            }
        }
        _running = false;
    }

    ~TcpServer()
    {
    }

private:
    ioserver_t _server;
    bool _running;
    unique_ptr<Socket> _sock;
    uint16_t _port;
};